"""
基础数据模型
包含公共的数据类型和基础模型类
"""
from bson import ObjectId
from typing import Any
from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema


class PyObjectId(ObjectId):
    """自定义ObjectId类型，用于Pydantic模型"""
    
    @classmethod
    def __get_validators__(cls):
        """Pydantic v1 兼容方法"""
        yield cls.validate

    @classmethod
    def validate(cls, v, *args, **kwargs):
        """兼容 Pydantic v1 和 v2 的验证方法"""
        if isinstance(v, ObjectId):
            return v
        if isinstance(v, str):
            if not ObjectId.is_valid(v):
                raise ValueError("Invalid ObjectId")
            return ObjectId(v)
        raise ValueError("Invalid ObjectId")

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source_type: Any, handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        """Pydantic v2 核心 schema 生成方法"""
        return core_schema.no_info_plain_validator_function(
            cls.validate,
            serialization=core_schema.to_string_ser_schema()
        )

    @classmethod
    def __get_pydantic_json_schema__(cls, core_schema, handler):
        """为Pydantic v2兼容的JSON Schema生成方法"""
        return {"type": "string", "format": "objectid"}

    @classmethod
    def __modify_schema__(cls, field_schema: dict) -> None:
        """为Pydantic v1兼容的Schema修改方法"""
        field_schema.update(type="string")
    
    def __str__(self):
        return str(super())
    
    def __repr__(self):
        return f"PyObjectId('{str(self)}')"